package org.endy.leisure.diaTracker.controller

import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import kotlinx.coroutines.reactor.mono
import org.endy.leisure.diaTracker.entity.User
import org.endy.leisure.diaTracker.entity.question.Image
import org.endy.leisure.diaTracker.entity.question.Question
import org.endy.leisure.diaTracker.service.QuestionService
import org.endy.leisure.diaTracker.util.CommUtils
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono

@Tag(name = "提问接口", description = "用于用户提交问题，医生回答问题")
@RestController
@RequestMapping("/question")
class QuestionController(private val questionService: QuestionService) {

    @Value("\${web.pic.dir:/data/nginx/www/images}")
    private lateinit var imgSavePath: String

    @Operation(summary = "创建问题", description = "用于用户提交问题")
    @PostMapping("/submit")
    fun createQuestion(@RequestBody request: QuestionRequest): Mono<WebResponse<Question>> = mono {
        // 将图片的base64编码图片进行解码存储到指定的路径
        val images = request.images?.withIndex()?.map { (idx, imgBase64Str) ->
            val imagePath = CommUtils.saveBase64ImageToFile(imgBase64Str, imgSavePath)
            Image(url = imagePath!!, order = idx)
        }?.toList()
        // 构建问题对象
        val question = Question(
            content = request.content,
            user = User(id = request.userId),
            images = images
        )
        WebResponse.success(questionService.createQuestion(question))
    }

    @Operation(summary = "用户的问题列表", description = "根据用户的id查询自己的问题列表")
    @PostMapping("/listByUserId")
    fun findUserQuestions(@RequestBody request: UserIdRequest): Mono<WebResponse<List<Question>>> = mono {
        WebResponse.success(questionService.findUserQ(request.userId))
    }

    @Operation(summary = "问题列表", description = "查询所有的问题列表")
    @PostMapping("/list")
    fun findAllQuestions(): Mono<WebResponse<List<Question>>> = mono {
        WebResponse.success(questionService.findAllQuestion())
    }

    @Operation(summary = "未回答问题列表", description = "查询所有还未回答的问题列表")
    @PostMapping("/noAnswerlist")
    fun findNoAnswerQuestions(): Mono<WebResponse<List<Question>>> = mono {
        WebResponse.success(questionService.findAllNoAnswerQuestion())
    }


    @Operation(summary = "回答问题", description = "用于医生回答问题")
    @PostMapping("/answer")
    fun answerQuestion(@RequestBody request: AnswerQuestionRequest): Mono<WebResponse<Void>> = mono {
        questionService.answerQ(request.id, request.userId, request.content)
        WebResponse.success(null)
    }
}
